﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Admin.Models;
using System.Data;

namespace BookStore.Admin.Controllers
{
    [HandleError]
    public class BookController : Controller
    {
        private int page = 0;
        private int notFound = 0;
        public ActionResult Index()
        {
            if (Session["Session_Admin"] == null) return RedirectToAction("index", "login");

            page = Convert.ToInt32(this.Request.QueryString["page"]);
            if (page == 0) page = 1;
            string sort = this.Request.QueryString["sort"];
            if (sort != "bn" && sort != "bc" && sort != "cn" && sort != "pb" &&
                sort != "pr" && sort != "qb" && sort != "qr" && sort != "st")
                sort = "bn";
            string type = this.Request.QueryString["type"];
            if (type != "asc" && type != "desc") type = "asc";
            string keyword = this.Request.QueryString["keyword"];
            if (keyword == null) keyword = "";

            ViewData["listBook"] = this.getAllBook();
            ViewData["sort"] = sort;
            ViewData["type"] = type == "asc" ? "desc" : "asc";
            ViewData["typeCur"] = type;
            ViewData["keyword"] = keyword;
            ViewData["page"] = page;

            if (this.Session["message"] != null)
            {
                ViewData["success"] = (int)this.Session["message"] == 1 ? "Cập nhật sách thành công !" : "";
                if (ViewData["success"] == "")
                    ViewData["success"] = (int)this.Session["message"] == 2 ? "Thêm sách mới thành công !" : "";
                ViewData["warning"] = (int)this.Session["message"] == -1 ? "Cập nhật sách thất bại ! Vui lòng thử lại !" : "";
                if (ViewData["warning"] == "")
                    ViewData["warning"] = (int)this.Session["message"] == -2 ? "Thêm sách mới thất bại ! Vui lòng thử lại !" : "";
                Session["message"] = null;
            }
            else
            {
                ViewData["success"] = "";
                ViewData["warning"] = "";
            }
            
            return View();
        }

        public ActionResult Detail()
        {
            if (Session["Session_Admin"] == null) return RedirectToAction("index", "login");

            string action = this.Request.QueryString["action"];
            if (action != "new" && action != "edit") action = "new";

            CategoriesModel tbCategory = new CategoriesModel();
            ViewData["allCate"] = tbCategory.getAllCategories();

            if (action == "edit")
            {
                int id = Convert.ToInt32(this.Request.QueryString["id"]);
                BookModel tbBook = new BookModel();
                string[] result = new string[14];
                result = tbBook.getBookbyID(id);
                if (result[0] == null) return RedirectToAction("index", "book");
                ViewData["book_code"] = result[0];
                ViewData["book_name"] = result[1];
                ViewData["author_name"] = result[2];
                ViewData["price_buy"] = result[3];
                ViewData["price_rent"] = result[4];
                ViewData["quantity"] = result[5];
                ViewData["quantity_rent"] = result[12];
                ViewData["image_url"] = result[7];
                ViewData["image_url_hidden"] = result[7].Substring(6);
                ViewData["status"] = result[8];
                ViewData["short_description"] = result[9];
                ViewData["long_description"] = result[10];
                ViewData["category_id"] = result[11];

                ViewData["book_id"] = id;
            }
            ViewData["action"] = action;

            return View();
        }

        [ValidateInput(false)]
        public ActionResult editBook()
        {
            if (Session["Session_Admin"] == null) return RedirectToAction("index", "login");
            
            if (this.Request.Form.Count != 0)
            {
                if (this.Request.Form["image_url"].Trim() != "")
                {
                    try
                    {
                        string path = Server.MapPath("~") + @"\Data\Temp\";
                        string Fromfile = path + this.Request.Form["image_url"];
                        string NewPath = Server.MapPath("~") + @"\Data\";
                        string Tofile = NewPath + this.Request.Form["image_url"];
                        System.IO.File.Move(Fromfile, Tofile);
                    }
                    catch (Exception err) { }
                    string[] filePaths = System.IO.Directory.GetFiles(Server.MapPath("~") + @"\Data\Temp\");
                    foreach (string filePath in filePaths)
                    {
                        try
                        {
                            System.IO.File.Delete(filePath);
                        }
                        catch (Exception err) { }
                    }
                    try
                    {
                        System.IO.File.Delete(Server.MapPath("~") + this.Request.Form["old_image_url"]);
                    }
                    catch (Exception err) { }
                }
                BookModel tbBook = new BookModel();

                string [] data = new string[13];
                data[0] = Server.HtmlEncode(this.Request.Form["book_code"]);
                data[1] = Server.HtmlEncode(this.Request.Form["book_name"]);
                data[2] = Server.HtmlEncode(this.Request.Form["author_name"]);
                data[3] = this.Request.Form["price_buy"];
                data[4] = this.Request.Form["price_rent"];
                data[5] = this.Request.Form["quantity"];
                data[6] = this.Request.Form["quantity_rent"];
                data[7] = "/Data/" + this.Request.Form["image_url"];
                data[8] = this.Request.Form["status"];
                data[9] = Server.HtmlEncode(this.Request.Form["short_description"]);
                data[10] = this.Request.Form["long_description"];
                data[11] = this.Request.Form["category_id"];
                data[12] = this.Request.Form["book_id"];

                this.Session["message"] = tbBook.editBook(data);
            }

            return RedirectToAction("index", "book");
        }

        [ValidateInput(false)]
        public ActionResult newBook()
        {
            if (Session["Session_Admin"] == null) return RedirectToAction("index", "login");

            if (this.Request.Form.Count != 0)
            {
                if (this.Request.Form["image_url"].Trim() != "")
                {
                    try
                    {
                        string path = Server.MapPath("~") + @"\Data\Temp\";
                        string Fromfile = path + this.Request.Form["image_url"];
                        string NewPath = Server.MapPath("~") + @"\Data\";
                        string Tofile = NewPath + this.Request.Form["image_url"];
                        System.IO.File.Move(Fromfile, Tofile);

                        string[] filePaths = System.IO.Directory.GetFiles(path);
                        foreach (string filePath in filePaths)
                        {
                            try
                            {
                                System.IO.File.Delete(filePath);
                            }
                            catch (Exception err) { }
                        }
                    }
                    catch (Exception err)
                    {
                        Session["message"] = -2;
                        return RedirectToAction("index", "book");
                    }
                }
                BookModel tbBook = new BookModel();

                string[] data = new string[12];
                data[0] = Server.HtmlEncode(this.Request.Form["book_code"]);
                data[1] = Server.HtmlEncode(this.Request.Form["book_name"]);
                data[2] = Server.HtmlEncode(this.Request.Form["author_name"]);
                data[3] = this.Request.Form["price_buy"];
                data[4] = this.Request.Form["price_rent"];
                data[5] = this.Request.Form["quantity"];
                data[6] = this.Request.Form["quantity_rent"];
                data[7] = "/Data/" + this.Request.Form["image_url"];
                data[8] = this.Request.Form["status"];
                data[9] = Server.HtmlEncode(this.Request.Form["short_description"]);
                data[10] = this.Request.Form["long_description"];
                data[11] = this.Request.Form["category_id"];

                this.Session["message"] = tbBook.newBook(data);
            }

            return RedirectToAction("index", "book");
        }

        public ActionResult jsonCheckCode()
        {
            if (Session["Session_Admin"] == null) return Content("-3");

            BookModel tbBook = new BookModel();
            int result = tbBook.checkBookCode(Convert.ToInt32(this.Request.QueryString["id"]), this.Request.QueryString["code"]);
            
            return Content(result.ToString());
        }

        public ActionResult jsonRenameFile()
        {
            if (Session["Session_Admin"] == null) return Content("-3");

            string NewName = "-1";
            try
            {
                string path = Server.MapPath("~") + @"\Data\Temp\";
                string Fromfile = path + this.Request.QueryString["name"];
                NewName = Utils.Now() + "_" + this.Request.QueryString["name"];
                string Tofile = path + NewName;
                System.IO.File.Move(Fromfile, Tofile);
            }
            catch (Exception err)
            {
                return Content("-1");
            }

            return Content(NewName);
        }

        public ActionResult jsonDeleteBook()
        {
            if (Session["Session_Admin"] == null) return Content("-3");

            BookModel tbBook = new BookModel();
            string tempData = tbBook.getBookURLImage(Convert.ToInt32(this.Request.QueryString["id"]));

            int result = tbBook.deleteBook(Convert.ToInt32(this.Request.QueryString["id"]));
            if (result == 1)
            {
                try
                {
                    System.IO.File.Delete(Server.MapPath("~") + tempData);
                }
                catch (Exception err) { }

                return Content(this.getAllBook());
            }
            else return Content(result.ToString());
        }

        public ActionResult deleteBooks()
        {
            if (Session["Session_Admin"] == null) return RedirectToAction("index", "login");

            BookModel tbBook = new BookModel();

            if (this.Request.Form["selected[]"] != null)
            {
                foreach (string value in this.Request.Form["selected[]"].Split(','))
                {
                    string tempData = tbBook.getBookURLImage(Convert.ToInt32(value));

                    tbBook.deleteBook(Convert.ToInt32(value));

                    try
                    {
                        System.IO.File.Delete(Server.MapPath("~") + tempData);
                    }
                    catch (Exception err) { }
                }
            }

            return RedirectToAction("index", "book");
        }

        private string getAllBook()
        {
            string html = "";

            string sort = this.Request.QueryString["sort"];
            if (sort != "bn" && sort != "bc" && sort != "cn" && sort != "pb" &&
                sort != "pr" && sort != "qb" && sort != "qr" && sort != "st")
                sort = "bn";
            string type = this.Request.QueryString["type"];
            if (type != "asc" && type != "desc") type = "asc";
            string keyword = this.Request.QueryString["keyword"];
            if (keyword == null) keyword = "";

            BookModel tbBook = new BookModel();
            int countBook = tbBook.countAllBook();
            if(notFound == 0)
                page = Convert.ToInt32(this.Request.QueryString["page"]);
            if (page == 0) page = 1;
            int limit = 12;
            Pagination pagination = new Pagination("/admin/book?keyword=" + keyword + "&sort=" + sort + "&type=" + type + "&page=", countBook, limit, page);

            string[][] resultBooks = tbBook.getAllBook(page, limit, sort, type, keyword);

            if (resultBooks[0] != null)
            {
                foreach (string[] row in resultBooks)
                {
                    if (row == null) break;
                    html += "<tr>";
                    html += "<td style='text-align: center;'>    ";
                    html += "    <input name='selected[]' value='" + row[6] + " ' type='checkbox' />";
                    html += " </td>";
                    html += "<td class='center'><img onerror=this.src='/content/images/no_image.jpg' src='" + row[7] + " ' style='padding: 1px; border: 1px solid rgb(221, 221, 221);' width='40' height='50'></td>";
                    html += "<td class='left'>" + row[0] + "</td>";
                    html += "<td class='left'>" + row[1] + "</td>";
                    html += "<td class='left'>" + row[11] + "</td>";
                    html += "<td class='left'>" + row[3] + "</td>";
                    html += " <td class='right'><span style='color: #008000;'>" + row[5] + " </span></td>";
                    html += " <td class='left'>" + row[4] + "</td>";
                    html += "  <td class='right'><span style='color: #008000;'>" + row[9] + " </span></td>";
                    html += " <td class='left'>" + row[10] + " </td>";
                    html += " <td class='right'>";
                    html += "     [ <a href='/admin/book/detail?id=" + row[6] + "&action=edit'>Sửa</a> ] ";
                    html += "     [ <a href='javascript:;' onclick='deleteBook(" + row[6] + " )'>Xoá</a> ]";
                    html += "  </td>";
                    html += " </tr>";
                }
            }
            else if (page == 1)
            {
                html += " <tr>";
                html += "    <td colspan='11' height='40' align='center'>Không có sách nào !  </td>  ";
                html += " </tr>  ";
            }
            else if(page > 0)
            {
                page--;
                notFound = 1;
                return this.getAllBook();
            }
            html += " <tr style='background-color:white;'>";
            html += "    <td colspan='11' height='40' align='center'>";
            html += "   <div class='pagination' style='width:98%;'>";
            html += pagination.render();
            html += "    </div> ";
            html += "   </td>  ";
            html += "</tr>  ";

            return html;
        }
    }
}
